package com.twu.biblioteca;

import java.util.*;

/**
 * Created by kathy on 12/04/14.
 */
public class CheckoutBookAction implements Action {

//    private List<Book> bookRepository;
//    private List<User> userList;

    private Library library;
    private IUserLogin userLogin;
    private IConsoleReader consoleReader;
    private IConsoleWriter consoleWriter;

    public  CheckoutBookAction(Library library, IConsoleReader consoleReader,
                               IConsoleWriter consoleWriter, IUserLogin userLogin) {
        this.library = library;

        this.consoleWriter = consoleWriter;
        this.consoleReader = consoleReader;
        this.userLogin = userLogin;
    }

    public void execute(){

        if(BibliotecaApp.currentUser != null) {
            consoleWriter.println("Please input the book id for checkout: ");
            String id = consoleReader.readInput().toLowerCase().trim();

            while (!checkoutBook(id, BibliotecaApp.currentUser) && !id.equals("menu")) {
                consoleWriter.println("That book is not available. Please re-input or enter 'menu' to back to main menu ");
                id = consoleReader.readInput();
            }
            if (!id.equals("menu"))
                consoleWriter.println("Thank you! Enjoy the book");
        }
    }


    // This method is to check out a book and returns true if it is successful
    public boolean checkoutBook(String bookId, User user){

        bookId = bookId.toLowerCase();

        for(Book aBook : library.getBookRepository()){
            if(aBook.getId().toString().toLowerCase().equals(bookId)
                    && aBook.getUser() == null) {
                aBook.setUser(user); // book is unavailable for others to borrow
                return true;
            }
        }
        return false;
    }
}
